package com.david.func_test.view

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView
import com.david.func_test.R

class FloatIconView : androidx.appcompat.widget.AppCompatImageView {
    lateinit var parent: ViewGroup

    var param: FrameLayout.LayoutParams? = null
    constructor(
        parent: ViewGroup, context: Context, attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : super(context, attrs, defStyleAttr) {
        this.parent = parent
    }

    constructor(context: Context) : super(context)

    init {
        setImageResource(R.mipmap.ic_launcher)
        scaleType = ScaleType.CENTER_CROP
    }

    private var inAnim: ValueAnimator? = null
    private var outAnim: ValueAnimator? = null

    /**
     * 调用接口检测是否需要显示
     */
    fun checkShow(recyclerView: RecyclerView) {
        param = FrameLayout.LayoutParams(152, 128)
        param?.gravity = Gravity.END or Gravity.BOTTOM
        param?.setMargins(0, 0, 0, 100)

        parent.addView(this, param)

        recyclerView.addOnScrollListener(scrollListener)
    }


    private var progress: Float = 0f
    private fun show() {
        if (outAnim?.isRunning == true) {
            outAnim?.cancel()
        } else if (inAnim?.isRunning == true) {
            return
        }

        inAnim = ValueAnimator.ofFloat(progress, 1f)
        inAnim?.duration = 300
        inAnim?.addUpdateListener {
            progress = it.animatedValue as Float
            setLocation()

            Log.e("test", progress.toString())
        }
        inAnim?.start()
    }

    fun hide() {
        if (inAnim?.isRunning == true) {
            inAnim?.cancel()
        } else if (outAnim?.isRunning == true) {
            return
        }

        outAnim = ValueAnimator.ofFloat(progress, 0f)
        outAnim?.duration = 300
        outAnim?.addUpdateListener {
            progress = it.animatedValue as Float
            setLocation()
        }
        outAnim?.start()
    }

    private fun setLocation() {
        param?.setMargins(0, 0, (progress * width - width).toInt(), 100)
        layoutParams = param
    }


    private val showTask = Runnable {
        show()
    }

    private val scrollListener = object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            removeCallbacks(showTask)
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                postDelayed(showTask, 300)
            } else {
                hide()
            }
        }
    }
}